"""
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################################
# Copyright (c) 2021 Huawei Technologies Co.,Ltd.
#
# openGauss is licensed under Mulan PSL v2.
# You can use this software according to the terms
# and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
#          http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
# ----------------------------------------------------------------------------
# Description  : download openGauss third party source before build.
#############################################################################
"""
import os.path
import shutil
import subprocess
import argparse

from xml.dom.minidom import parse
import xml.dom.minidom

class DownThirdParty:

    def __init__(self):
        self.library_list = []
        self.filter_libs = []

    def parse_args(self):
        parser = argparse.ArgumentParser(description="""
            Download third party source file.""")
        parser.add_argument('--libs', type=str, required=False, help='assign third party library. Default all.')
        parser.add_argument('-L', action='store_true', required=False, help='list all librarys')
        return parser.parse_args()

    def parse_xml(self):
        dom_tree = xml.dom.minidom.parse("third_party.xml")
        collection = dom_tree.documentElement

        library_ele_list = collection.getElementsByTagName("library")

        for lib in library_ele_list:
            name_ele = lib.getElementsByTagName("name")[0]
            name = name_ele.childNodes[0].data
            if lib.getElementsByTagName("disable"):

                continue
            path_ele = lib.getElementsByTagName("path")[0]
            path = path_ele.childNodes[0].data
            ver_ele = lib.getElementsByTagName("version")[0]
            version = ver_ele.childNodes[0].data
            down_ele = lib.getElementsByTagName("download")[0]
            downlink = down_ele.childNodes[0].data
            source_ele = lib.getElementsByTagName("source_code_path")[0]
            source_path = source_ele.childNodes[0].data
            self.library_list.append([name, version, path, downlink, source_path])

    def download_source(self):
        index = 0
        for item in self.library_list:
            name = item[0]
            if len(self.filter_libs) > 0 and name not in self.filter_libs:
                continue
            pkgname = item[1]
            source_path = item[4]
            downlink = item[3]
            type_path = item[2]
            cmd = "wget -c %s -O %s" % (downlink, pkgname)
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0:
                print("... [%-30s] download failed ..." % name)
                print(cmd)
                print(status, output)
            else:
                print("... [%-30s] download success ..." % name)
                # target_path = os.path.join(type_path, name)
                # target_pkg = os.path.join(target_path, pkgname)
                # if os.path.exists(target_pkg):
                #     os.remove(target_pkg)
                # shutil.move(pkgname, target_path)
                # tar_cmd = """
                # cd %s; mkdir %s; tar -xf %s -C %s --strip-components 1
                # """ % (target_path,
                #        source_path,
                #        pkgname,
                #        source_path
                #        )
                # (status, output) = subprocess.getstatusoutput(tar_cmd)
                # if status != 0:
                #     print("... [%-30s] decompression failed ..." % name)
                # else:
                #     print("... [%-30s] decompression success ..." % name)
            index += 1
        if index == 0:
            print("no third party source will download.")

    def display_libs(self):
        print("%-30s%-40s%-20s" % ("name", "package name", "download link"))
        print("%-30s%-40s%-20s" % ("---------------", "--------------------",
                                   "-------------------------------"))
        for item in self.library_list:
            name = item[0]
            pkgname = item[1]
            downlink = item[3]
            if len(self.filter_libs) > 0 and name not in self.filter_libs:
                continue
            print("%-30s%-40s%-20s" % (name, pkgname, downlink))

    def run(self):
        params = self.parse_args()
        libstr = params.libs
        if libstr and libstr.strip() != "all":
            self.filter_libs = libstr.split(",")
        self.parse_xml()
        if params.L:
            self.display_libs()
            return

        self.download_source()


if __name__ == '__main__':
    down3rd = DownThirdParty()
    down3rd.run()

